package com.xhs.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.xhs.dto.request.PageUserParams;
import com.xhs.entity.SysUserEntity;
import com.xhs.enums.CommonSortOrderEnum;
import com.xhs.mapper.SysUserMapper;
import com.xhs.message.ReturnResult;
import com.xhs.service.SysUserService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import static com.mybatisflex.core.query.QueryMethods.noCondition;
import static com.xhs.entity.table.SysUserEntityTableDef.SYS_USER_ENTITY;

/**
 * 系统用户表 服务层实现。
 *
 * @author xhs
 * @since 2025-06-09
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserEntity> implements SysUserService {

    /**
     * 分页查询用户
     *
     * @param pageUserParams 查询条件
     * @return ReturnResult<Object>
     */
    @Override
    public ReturnResult<Object> pageList(PageUserParams pageUserParams) {
        Page<SysUserEntity> page = new Page<>(pageUserParams.getPageNumber(), pageUserParams.getPageSize());
        // 处理排序
        boolean sort = false;
        if (ObjectUtil.isAllNotEmpty(pageUserParams.getSortOrder(), pageUserParams.getSortField())) {
            CommonSortOrderEnum.validate(pageUserParams.getSortOrder());
            sort = true;
        }
        Page<SysUserEntity> entityPage = queryChain()
                .select(SYS_USER_ENTITY.DEFAULT_COLUMNS)
                .from(SYS_USER_ENTITY)
                .where(StringUtils.hasLength(pageUserParams.getUserName()) ? SYS_USER_ENTITY.USER_NAME.like(pageUserParams.getUserName()) : noCondition())
                .and(StringUtils.hasLength(pageUserParams.getJobNumber()) ? SYS_USER_ENTITY.JOB_NUMBER.like(pageUserParams.getJobNumber()) : noCondition())
                .and(StringUtils.hasLength(pageUserParams.getPhone()) ? SYS_USER_ENTITY.PHONE.like(pageUserParams.getPhone()) : noCondition())
                .and(pageUserParams.getEmploymentStatus() != null ? SYS_USER_ENTITY.EMPLOYMENT_STATUS.like(pageUserParams.getEmploymentStatus()) : noCondition())
                .orderBy(sort ? StrUtil.toUnderlineCase(pageUserParams.getSortField()) : "", sort ?
                        pageUserParams.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()) : null)
                .page(page);
        return ReturnResult.success().setData(entityPage);
    }
}
